import network
import time
import ntptime
import urequests
import ujson
from machine import RTC
from DateTime import days_in_month,datetime_to_seconds
class esp32_wifi(object):
    ssid=""
    password = ""
    last_synctime = None
    lasttime_weather = None
    weather_interval = 1800
    time_sync = 3600		#  自动同步时间间隔（秒）
    is_time_sync = False
    def __init__(self,mode="STA_MODE",esp32ssid="ESP32C3-AP",esp32psw = "doyouknow",esp32authmode=network.AUTH_WPA_WPA2_PSK):
        if mode == "STA_MODE":
            self.wlan = network.WLAN(network.STA_IF)
            self.wlan.active(True)
            ssid,password = self.load_wificonfig()
            if ssid and password:
                print(ssid,password)
                self.wlan.connect(ssid,password)
                self.ssid = ssid
                self.password = password
        elif mode == "AP_MODE":
            self.ap = network.WLAN(network.AP_IF)
            self.ap.config(essid = esp32ssid,password = esp32psw,authmode = esp32authmode)
            self.ap.active(True)
            self.ssid = esp32ssid
            self.password = esp32psw
            self.authmode = esp32authmode
            print("ESP32C3 AP IP地址：",self.ap.ifconfig()[0])
        
        
    def  scanwifi(self):
        networks = self.wlan.scan()
        for net in networks:
                print(net[0],net[3])
    
    def  configwifi(self,ssid,password):
        if not self.wlan.isconnected():
            self.ssid = ssid
            self.password = password
            print(" 正在连接到",ssid)
            self.wlan.connect(self.ssid,self.password)
            
            max_wait = 10
            while max_wait > 0:
                if self.wlan.isconnected():
                    break
                max_wait -= 1
                print("等待连接……",max_wait)
                time.sleep(1)
            if not self.wlan.isconnected():
                print("连接失败")
            else:
                print("连接成功")
            
    def  check_wifi(self):
        if self.wlan.isconnected():
#            print("网络配置:",self.wlan.ifconfig())
            return True
#            print("已连接到网络")
#            print("IP地址：",self.wlan.ifconfig()[0])
#            print("子网掩码：",self.wlan.ifconfig()[1])
#            print("网关：",self.wlan.ifconfig()[2])
#            print("DNS：",self.wlan.ifconfig()[3])
        else:
            return False
#            print("未连接到网络")
#            self.configwifi(self.ssid,self.password)
            
    def save_wificonfig(self):
          with open ("wificonfig.txt","w") as f:
              f.write(self.ssid+"\n")
              f.write(self.password+"\n")
              
    def  load_wificonfig(self):
        try:
            with open("wificonfig.txt","r") as f:
                ssid = f.readline().strip()
                password = f.readline().strip()
                return ssid,password
        except:
            return None,None

    def auto_sync_time(self,max_retries = 3,retry_delay=10):
        #max_retries: 最大重试次数
        #retry_delay:重试间隔（秒）
        retry = 0
        while retry < max_retries:
            if self.sync_time_with_timezone(8):
                return True
            retry += 1
            time.sleep(retry_delay)
        return False

    def sync_ntp_time(self):
        if not self.wlan.isconnected():
            print("未连接到网络，请检测网络")
            return False
        
        try:
            ntptime.host = "ntp.aliyun.com"
            ntptime.settime()
            
            rtc = RTC()
            print("同步成功！当前时间：",rtc.datetime())
            self.is_time_sync = True
            return True
        except Exception as e:
            self.is_time_sync = False
            print("时间同步失败：",e)
            return False

    def sync_time_with_timezone(self,offset=8):
#    同步时间并设置时区
#    offset: 时区偏移(小时)，东八区为8
        if not self.wlan.isconnected():
#            print("未连接到网络，请检测网络")
            return False
        try:
            ntptime.host = "ntp.aliyun.com"
            ntptime.settime()
            rtc = RTC()
            tm = list(rtc.datetime())
            
            # 调整时区
            tm[4] += offset  # 增加小时偏移
            if tm[4] >= 24:
                tm[4] -= 24
                tm[2] += 1  # 增加一天
            
            rtc.datetime(tuple(tm))
            self.is_time_sync = True
#            print("时间同步成功(UTC+%d):" % offset, rtc.datetime())
            return True
        except Exception as e:
            self.is_time_sync = False
            print("时间同步失败:", e)
            return False    

    def periodic_time_sync(self,interval=0):
        #定期同步时间，interval :同步时间间隔（秒），默认1小时
        if interval != 0:
            self.time_sync = interval
        if self.is_time_sync:
            if self.last_synctime != None:
                rtc = RTC()
                if datetime_to_seconds(rtc.datetime()) - datetime_to_seconds(self.last_synctime) < self.time_sync:
                    return
                
        if self.auto_sync_time():
#            print("同步时间成功，当前时间：",self.format_time())
            rtc = RTC()
            self.last_synctime = rtc.datetime()
#            print("同步时间：",self.format_datetime())
            
    def GetWeather(self,location="shenzhen",interval=0):
        if not self.wlan.isconnected():
#      	print("未连接到网络，请检测网络")
            return False
        if interval != 0:
            self.weather_interval = interval
        if self.is_time_sync:
            rtc = RTC()
            if (self.lasttime_weather is not None):
                if datetime_to_seconds(rtc.datetime()) - datetime_to_seconds(self.lasttime_weather) < self.weather_interval:
                    return False
            try:
                result3=urequests.get('https://api.seniverse.com/v3/weather/now.json?key=Sxkfy_sm3F1cKC7-l&location='+location+'&language=zh-Hans&unit=c')
                j3=ujson.loads(result3.text)
                self.lasttime_weather = rtc.datetime()
#                print(self.lasttime_weather)
                return j3
            except Exception as e:
                print("获取天气信息失败:", e)
                return False    
        else:
            return False

'''
        print(j3['results'][0]['location']['name'],end=' ')
        print(j3['results'][0]['now']['text'],end=' ')
        print(j3['results'][0]['now']['temperature'],end='℃ ')
    #    print(j3['results'][0]['now']['pressure'],end='Pa ')
    #    print(j3['results'][0]['now']['humidity'],end='% ')
    #    print(j3['results'][0]['now']['wind_speed'],end=' ')
        
        print(j3['results'][0]['last_update'])
'''   
